package com.example.test3.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.test3.R;
import com.example.test3.adapter.Song;
import com.example.test3.adapter.SongAdapter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    private List<Song> songList=new ArrayList<>();
    private MediaPlayer mediaPlayer=new MediaPlayer();
    public int position=-1;
    public int m=0;
    private SeekBar seekBar;
    private boolean isSeekBarChanging;
    private int currentPosition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        seekBar = (SeekBar) findViewById(R.id.seekbar);
        seekBar.setOnSeekBarChangeListener(new MySeekBar());
    }


    //加入歌曲的操作
    private void initSongs() {
        Song apple=new Song("4円 (ヨエン) - アイロニ (反语).mp3");
        songList.add(apple);
        Song a=new Song("张碧晨 - 不要忘记我爱你.mp3");
        songList.add(a);
        Song b=new Song("薛之谦 - 天后 (Live).mp3");
        songList.add(b);
        Song c=new Song("薛之谦 - 方圆几里.mp3");
        songList.add(c);
        Song d=new Song("锦零 - 世界上的另一个我.mp3");
        songList.add(d);
        Song e=new Song("陈一发儿 - 童话镇.MP3");
        songList.add(e);
        SongAdapter adapter=new SongAdapter(MainActivity.this,R.layout.song_list,songList);
        ListView listView=findViewById(R.id.song_list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
                position=pos;
                play(position);
            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int pos, long l) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("你真的要删除他吗？");
                builder.setNegativeButton("取消", null);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        songList.remove(pos);
                        adapter.notifyDataSetChanged();
                        mediaPlayer.pause();
                    }
                });
                builder.show();
                return false;
            }
        });

    }

    public void play(int pos){
        seekBar.setProgress(0);
        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.start();//开始播放
            mediaPlayer.seekTo(currentPosition);

            //监听播放时回调函数
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {

                Runnable updateUI = new Runnable() {
                    @Override
                    public void run() {
//                        musicCur.setText(format.format(mediaPlayer.getCurrentPosition()) + "");
                    }
                };

                @Override
                public void run() {
                    if (!isSeekBarChanging) {
                        seekBar.setMax(mediaPlayer.getDuration());
                        seekBar.setProgress(mediaPlayer.getCurrentPosition());
                        runOnUiThread(updateUI);
                    }
                }
            }, 0, 50);
        }
        TextView textView_name=findViewById(R.id.textview_Name);
        Song song = songList.get(pos);
        try {
            mediaPlayer.reset();
            mediaPlayer.setLooping(true);
            AssetManager assetManager=getAssets();
            AssetFileDescriptor assetFileDescriptor = assetManager.openFd(song.getName());
            textView_name.setText(song.getName());
            mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
            mediaPlayer.prepare();
            mediaPlayer.start();


        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 选项菜单
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    /**
    *点击后跳转到对应的新增歌曲界面*
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.insert:
                initSongs();     //初始化歌曲数据
                Toast.makeText(this, "插入歌曲", Toast.LENGTH_LONG).show();//暂时测试
                break;
            case R.id.help:
                new AlertDialog.Builder(this)
                        .setMessage("这是帮助")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("确定", null)
                        .show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }




public class MySeekBar implements SeekBar.OnSeekBarChangeListener {

    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    }

    /*滚动时,应当暂停后台定时器*/
    public void onStartTrackingTouch(SeekBar seekBar) {
        isSeekBarChanging = true;
    }

    /*滑动结束后，重新设置值*/
    public void onStopTrackingTouch(SeekBar seekBar) {
        seekBar.setMax(mediaPlayer.getDuration());
        isSeekBarChanging = false;
        mediaPlayer.seekTo(seekBar.getProgress());
    }
}
    /**
     *下面是各种按钮触发事件
     */




        public void next(View view){
        if(songList.size()==0){
            Toast.makeText(this, "请先插入歌曲", Toast.LENGTH_LONG).show();
        }
        else{
            if(m==0){
                if(position<songList.size()-1){
                    position+=1;
                    play(position);
                }
                else{
                    position=0;
                    play(position);
                }
            }
            else if(m==1){
                position= new Random().nextInt(songList.size());
                play(position);
            }
        }
    }

    public void previous(View view){
        if(songList.size()==0){
            Toast.makeText(this, "请先插入歌曲", Toast.LENGTH_LONG).show();
        }
        else{
            if(m==0){
                if(position>0){
                    position-=1;
                    play(position);
                }
                else{
                    position=songList.size()-1;
                    play(position);
                }
            }
            else if(m==1){
                position= new Random().nextInt(songList.size());
                play(position);
            }
        }
    }

    public void switchClick(View view){
        if(mediaPlayer.isPlaying()){
            mediaPlayer.pause();
        }
        else{
            mediaPlayer.start();
        }
    }

    public void playMode(View view){
        if(m==0){
            m=1;
            Toast.makeText(this, "随机播放", Toast.LENGTH_LONG).show();
        }
        else if(m==1){
            m=0;
            Toast.makeText(this, "循环播放", Toast.LENGTH_LONG).show();
        }
    }


}